import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';
// 接口
import { fetchShopCart, fetchShopAddcart, fetchShopDelcart } from '~/request/api';

Page({
  data: {
    cartGroupData: null,
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow() { },

  onLoad() {
    this.refreshData();
  },

  // 添加购物车
  async shopAddcart({ goods_id, num }) {
    try {
      await fetchShopAddcart({ goods_id, num });
      return true;
    } catch (error) {
      console.log(error);
    }
    return false;
  },

  // 获取购物车信息
  async getShopCart() {
    try {
      const res = await fetchShopCart();
      const cartGroupData = {
        invalidGoodItems: [],
        storeGoods: [{ shortageGoodsList: [], promotionGoodsList: [{ goodsPromotionList: res }] }],
      };
      let isEmpty = true;
      for (const store of cartGroupData.storeGoods) {
        store.isSelected = true; // 该门店已加购商品是否全选
        store.storeStockShortage = false; // 该门店已加购商品是否存在库存不足
        if (!store.shortageGoodsList) {
          store.shortageGoodsList = []; // 该门店已加购商品如果库存为0需单独分组
        }
        for (const activity of store.promotionGoodsList) {
          activity.goodsPromotionList = activity.goodsPromotionList.filter((goods) => {
            goods.market_price = undefined;

            // 统计是否有加购数大于库存数的商品
            if (goods.num > goods.stock) {
              store.storeStockShortage = true;
            }
            // 统计是否全选
            if (!goods.isSelected) {
              store.isSelected = false;
            }
            // 库存为0（无货）的商品单独分组
            if (goods.stock > 0) {
              return true;
            }
            store.shortageGoodsList.push(goods);
            return false;
          });

          if (activity.goodsPromotionList.length > 0) {
            isEmpty = false;
          }
        }
        if (store.shortageGoodsList.length > 0) {
          isEmpty = false;
        }
      }
      cartGroupData.invalidGoodItems = cartGroupData.invalidGoodItems.map((goods) => {
        goods.market_price = undefined;
        return goods;
      });
      cartGroupData.isNotEmpty = !isEmpty;
      cartGroupData.totalAmount = 0;
      cartGroupData.selectedGoodsCount = 0;
      this.setData({ cartGroupData });
    } catch (error) {
      console.log(error);
    }
  },

  refreshData() {
    this.getShopCart();
  },

  // 数量过滤函数
  async stepsGoods(id, num) {
    const { cartGroupData } = this.data;
    const { storeGoods } = cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        for (const goods of activity.goodsPromotionList) {
          // 单选
          if (goods.id === id && goods.status === 1) {
            const status = await this.shopAddcart({ goods_id: goods.id, num });
            console.log(status);
            if (status) {
              // 加购数量等于库存数量的情况下继续加购
              if (goods.num > goods.stock) {
                Toast({
                  context: this,
                  selector: '#t-toast',
                  message: '当前商品库存不足',
                });
                return;
              }
              // 计算金额
              if (goods.isSelected) {
                if (goods.num < num) {
                  cartGroupData.totalAmount += +goods.sale_price;
                  cartGroupData.selectedGoodsCount += 1;
                } else {
                  cartGroupData.totalAmount -= +goods.sale_price;
                  cartGroupData.selectedGoodsCount -= 1;
                }
              }
              goods.num = num;
            } else {
              return false;
            }
          }
        }
      }
    }
    return cartGroupData;
  },

  // select过滤函数
  selectGoods(id, isSelected) {
    const { cartGroupData } = this.data;
    const { storeGoods } = cartGroupData;
    let isSelectStatus = 0;
    let listLen = 0;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        listLen = activity.goodsPromotionList.filter((item) => item.status == 1).length;
        // 计算总金额
        if (id === 'all') {
          cartGroupData.totalAmount = 0;
          cartGroupData.selectedGoodsCount = 0;
          if (isSelected) {
            activity.goodsPromotionList.forEach((item) => {
              cartGroupData.totalAmount += +item.sale_price * item.num;
              cartGroupData.selectedGoodsCount += item.num;
            });
          }
        }
        for (const goods of activity.goodsPromotionList) {
          // 全选
          if (id === 'all' && goods.status === 1) {
            goods.isSelected = isSelected;
          }
          // 单选
          if (goods.id === id && goods.status === 1) {
            goods.isSelected = isSelected;
            // 计算金额
            if (isSelected) {
              cartGroupData.totalAmount += +goods.sale_price * goods.num;
              // 计算勾选的数量
              cartGroupData.selectedGoodsCount += goods.num;
            } else {
              cartGroupData.totalAmount -= +goods.sale_price * goods.num;
              // 计算勾选的数量
              cartGroupData.selectedGoodsCount -= goods.num;
            }
          }
          if (goods.isSelected) {
            isSelectStatus += 1;
          }
        }
      }
    }
    cartGroupData.isAllSelected = false;
    // 如果勾选的数量和购物车数量长度一致则全选按钮勾选
    if (listLen === isSelectStatus) cartGroupData.isAllSelected = true;
    return cartGroupData;
  },

  // 删除过滤
  delGoods(id) {
    const { cartGroupData } = this.data;
    const { storeGoods } = cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        activity.goodsPromotionList = activity.goodsPromotionList.filter((goods) => goods.id !== id);
      }
    }
    return cartGroupData;
  },

  // 清空失效商品
  // 注：实际场景时应该调用接口
  clearInvalidGoodsService() {
    this.data.cartGroupData.invalidGoodItems = [];
    return Promise.resolve();
  },

  // 单选
  onGoodsSelect(e) {
    const {
      goods: { id },
      isSelected,
    } = e.detail;
    const info = this.selectGoods(id, isSelected);
    this.setData({ cartGroupData: info });
  },

  // 数量变化回调
  onQuantityChange(e) {
    const {
      goods: { id },
      quantity,
    } = e.detail;
    const info = this.stepsGoods(id, quantity);
    if (!info) {
      this.setData({ cartGroupData: info });
    }
  },

  goGoodsDetail(e) {
    const { goods } = e.detail;
    wx.navigateTo({
      url: `/pages/goods/details/index?goods_id=${goods.good_id}`,
    });
  },

  clearInvalidGoods() {
    // 实际场景时应该调用接口清空失效商品
    this.clearInvalidGoodsService().then(() => this.refreshData());
  },

  async shopDelcart(id) {
    try {
      await fetchShopDelcart({ cart_id: id });
      const info = this.delGoods(id);
      this.setData({ cartGroupData: info });
      Toast({ context: this, selector: '#t-toast', message: '商品删除成功' });
    } catch (error) {
      console.log(error);
    }
  },

  onGoodsDelete(e) {
    const {
      goods: { id },
    } = e.detail;
    Dialog.confirm({
      content: '确认删除该商品吗?',
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(() => {
      this.shopDelcart(id);
    });
  },

  // 全选
  onSelectAll(event) {
    const { isAllSelected } = event?.detail ?? {};
    // 调用接口改变全选
    const info = this.selectGoods('all', !isAllSelected);
    info.isAllSelected = !isAllSelected;
    this.setData({ cartGroupData: info });
  },

  // 去结算
  onToSettle() {
    const goodsRequestList = [];
    this.data.cartGroupData.storeGoods.forEach((store) => {
      store.promotionGoodsList.forEach((promotion) => {
        promotion.goodsPromotionList.forEach((m, i) => {
          if (m.isSelected) {
            goodsRequestList.push(m.id);
          }
        });
      });
    });
    if (!goodsRequestList.length) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请勾选商品！',
      });
      return;
    }
    let cart_ids = goodsRequestList.join(',');
    wx.navigateTo({ url: `/pages/order/order-confirm/index?cart_ids=${cart_ids}` });
  },
  onGotoHome() {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
